package edu.pku.sei.modeler.jet.codegen;

import java.io.ByteArrayInputStream;
import java.util.Iterator;
import java.util.Vector;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.codegen.jet.JETEmitter;

import edu.pku.sei.modeler.codegen.Activator;
import edu.pku.sei.modeler.jet.util.PackageRetriever;
import edu.pku.sei.modeler.model.core.CorePackage;
import edu.pku.sei.modeler.model.core.MetaEnum;
import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaModelElement;

public class GenEnumerationCode extends AbstractGenerator {
	private MetaModel model;
	
	public void setModelList(MetaModel model) {
		this.model = model;
	}
	
	private translated.EnumGen genEnum = translated.EnumGen.create("\n");
	
	@Override
	public void generateCode(IProgressMonitor monitor)
			throws InterruptedException {
		try {
			/*String relativeUri = "templates/model/Enum.javajet";
			String pluginId = Activator.getPluginId();
			JETEmitter emitter = new JETEmitter(templatesBase + relativeUri, Activator.getDefault().getClass().getClassLoader());
			emitter.addVariable("JET_TUTORIAL", pluginId);
			emitter.addVariable("JET_TUTORIAL", "edu.pku.sei.modeler.runtime");
			emitter.addVariable("EMF_ECORE", "org.eclipse.emf.ecore");
			emitter.addVariable("EMF_COMMON", "org.eclipse.emf.common");*/
			
			assert proj != null;
			assert model != null;
			
			IFolder folder = proj.getFolder("src");
			Vector<MetaModelElement> modelList = new Vector<MetaModelElement>();
			modelList.addAll(model.getInstancesForType(CorePackage.__METAENUM__));
			
			
			for (Iterator iter = modelList.iterator(); iter.hasNext();) {
				MetaEnum cls = (MetaEnum)iter.next();
				//String result = emitter.generate(monitor, new Object[]{cls});
				String result = genEnum.generate(cls);
								
				String pkgStr = PackageRetriever.retrievePackage(cls);
				pkgStr = pkgStr.replace('.', '/');
				IFolder theFolder = folder.getFolder(pkgStr);
				IFile javaFile = theFolder.getFile(cls.getName()+".java");
				
				ByteArrayInputStream is = new ByteArrayInputStream(result.getBytes());
				javaFile.create(is, true, monitor);
			}			
		} catch (Exception e) {
			e.printStackTrace();
			throw new InterruptedException("generate model code failed");
		}
	}

}
